package com.iuhao.rabbitMQ;

import com.iuhao.rabbitMQ.config.AmqpConfig;
import org.apache.log4j.Logger;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

/**
 * Used for loading and init mybatis
 *
 * @author Liu Jianwei<liujianwei@credit.com>
 * @date 2016-3-31
 */
@Configuration
@ComponentScan
@EnableConfigurationProperties({RabbitMQProperties.class})
public class RabbitMQConfiguration {

    private static final Logger logger = Logger.getLogger(RabbitMQConfiguration.class);

    @Autowired
    RabbitMQProperties rabbitMQProperties;

    public RabbitMQConfiguration() {
    }

    @Bean(name = "connectionFactory")
    public ConnectionFactory getConnectionFactory() {
        logger.info("====> Load and init RabbitMQ: " + rabbitMQProperties.getHost());
        CachingConnectionFactory factory = new CachingConnectionFactory();
        factory.setHost(rabbitMQProperties.getHost());
        factory.setUsername(rabbitMQProperties.getUsername());
        factory.setPassword(rabbitMQProperties.getPassword());
        factory.setVirtualHost(rabbitMQProperties.getVirtualHost());
        factory.setPublisherConfirms(true);
        factory.setPublisherReturns(true);
        return factory;
    }

    @Bean(name = "rabbitTemplate")
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setExchange(AmqpConfig.WLD_EXCHANGE);
        return rabbitTemplate;
    }

}
